/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.shuyihui.rxhttp.request

import com.shuyihui.rxhttp.callback.CallBack
import com.shuyihui.rxhttp.func.RetryExceptionFunc
import com.shuyihui.rxhttp.subsciber.DownloadSubscriber
import com.shuyihui.rxhttp.transformer.HandleErrTransformer
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody

/**
 *
 * 描述：下载请求
 */
class DownloadRequest(url: String?) : BaseRequest<DownloadRequest>(url) {
    private var savePath: String? = null
    private var saveName: String? = null

    /**
     * 下载文件路径<br></br>
     * 默认在：/storage/emulated/0/Android/data/包名/files/1494647767055<br></br>
     */
    fun savePath(savePath: String?): DownloadRequest {
        this.savePath = savePath
        return this
    }

    /**
     * 下载文件名称<br></br>
     * 默认名字是时间戳生成的<br></br>
     */
    fun saveName(saveName: String?): DownloadRequest {
        this.saveName = saveName
        return this
    }

    fun <T> execute(callBack: CallBack<T?>?): Disposable {
        return build()!!.generateRequest()!!
            .compose<ResponseBody?> { upstream ->
                if (isSyncRequest) {
                    upstream //.observeOn(AndroidSchedulers.mainThread());
                } else {
                    upstream.subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(Schedulers.computation())
                }
            }.compose(HandleErrTransformer()).retryWhen(
                RetryExceptionFunc(
                    retryCount,
                    retryDelay.toLong(),
                    retryIncreaseDelay.toLong()
                )
            )
            .subscribeWith(
                DownloadSubscriber<ResponseBody>(
                    context,
                    savePath!!,
                    saveName!!,
                    callBack
                )
            ) as Disposable
    }

    override fun generateRequest(): Observable<ResponseBody?>? {
        return apiManager!!.downloadFile(url!!)
    }
}